<template>
  <div class="v-tabs" :type="type" ref="input">
    <div class="tabs">
      <div class="tab" :class="{active:t[tabValue]==value}" v-for="(t,i) in list" :key="i" @click="select(t[tabValue])" ref="tabs">
        <slot :data="t" v-if="'default' in $scopedSlots"/>
        <div class="" v-else>{{t[tabLabel]}}</div>
      </div>
    </div>
    <slot name="slider" :data="sliderStyle" v-if="'slider' in $scopedSlots"/>
    <div class="slider" :style="{width:`${sliderStyle.width}px`,transform:`translate3d(${sliderStyle.left}px,0,0)`}" v-else></div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      default: 0
    },
    type: null,
    tabs: {
      default() {
        return [];
      }
    },
    tabLabel: {
      default: "label"
    },
    tabValue: {
      default: "value"
    }
  },
  data() {
    return {
      sliderStyle: {}
    };
  },
  computed: {
    list() {
      return this.tabs.map(
        (t, v) =>
          t instanceof Object ? t : { [this.tabLabel]: t, [this.tabValue]: v }
      );
    },
    tab() {
      return this.$refs.tabs[
        this.list.reduce(
          (p, o, i) => (o[this.tabValue] == this.value ? i : p),
          -1
        )
      ];
    }
  },
  watch: {
    ["value"](value) {
      this.select(value);
    }
  },
  methods: {
    select(v) {
      this.$emit("input", v);
      this.$emit("change", v);
      this.tab && this.tab.scrollIntoViewIfNeeded();
      this.setSliderStyle();
    },
    setSliderStyle() {
      this.sliderStyle = this.tab
        ? {
            left: this.tab.offsetLeft,
            width: this.tab.offsetWidth
          }
        : { left: 0, width: 0 };
    }
  },
  mounted() {
    this.setSliderStyle();
  }
};
</script>

<style lang="less">
.v-tabs {
  overflow: auto;
  position: relative;
  background-color: #ffffff;
  > .tabs {
    white-space: nowrap;
    > .tab {
      color: #666666;
      padding: 18px 10px;
      display: inline-block;
      &.active {
        color: #ff9b2f;
      }
    }
  }
  > .slider {
    bottom: 0px;
    min-height: 2px;
    position: absolute;
    background-color: #ff9b2f;
    transition: 300ms;
  }
  &[type="space-around"] {
    > .tabs {
      display: flex;
      justify-content: space-around;
    }
  }
}
</style>
